/**
 * 日期时间工具函数
 */

/**
 * 格式化日期时间
 * @param {Date} date 日期对象
 * @param {string} format 格式化模板，默认 'YYYY-MM-DD HH:mm:ss'
 * @returns {string} 格式化后的日期时间字符串
 */
export const formatDateTime = (date, format = 'YYYY-MM-DD HH:mm:ss') => {
  if (!date || !(date instanceof Date)) {
    return ''
  }

  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')

  return format
    .replace('YYYY', year)
    .replace('MM', month)
    .replace('DD', day)
    .replace('HH', hours)
    .replace('mm', minutes)
    .replace('ss', seconds)
}

/**
 * 获取当前月份的第一天（零点零分零秒）
 * @returns {string} 格式化后的日期时间字符串 'YYYY-MM-DD 00:00:00'
 */
export const getCurrentMonthFirstDay = () => {
  const now = new Date()
  const firstDay = new Date(now.getFullYear(), now.getMonth(), 1, 0, 0, 0)
  return formatDateTime(firstDay)
}

/**
 * 获取当前实时时间
 * @returns {string} 格式化后的日期时间字符串 'YYYY-MM-DD HH:mm:ss'
 */
export const getCurrentDateTime = () => {
  const now = new Date()
  return formatDateTime(now)
}

/**
 * 获取指定月份的第一天和最后一天
 * @param {number} year 年份
 * @param {number} month 月份（1-12）
 * @returns {Object} { startTime: string, endTime: string }
 */
export const getMonthRange = (year, month) => {
  const firstDay = new Date(year, month - 1, 1, 0, 0, 0)
  const lastDay = new Date(year, month, 0, 23, 59, 59)
  
  return {
    startTime: formatDateTime(firstDay),
    endTime: formatDateTime(lastDay)
  }
}

/**
 * 获取当前月份的时间范围（从月初到当前时间）
 * @returns {Object} { startTime: string, endTime: string }
 */
export const getCurrentMonthRange = () => {
  return {
    startTime: getCurrentMonthFirstDay(),
    endTime: getCurrentDateTime()
  }
}

/**
 * 获取指定天数前的日期时间
 * @param {number} days 天数
 * @param {boolean} startOfDay 是否返回当天的开始时间（00:00:00）
 * @returns {string} 格式化后的日期时间字符串
 */
export const getDaysAgo = (days, startOfDay = false) => {
  const now = new Date()
  const targetDate = new Date(now.getTime() - days * 24 * 60 * 60 * 1000)
  
  if (startOfDay) {
    targetDate.setHours(0, 0, 0, 0)
  }
  
  return formatDateTime(targetDate)
}

/**
 * 获取今天的开始和结束时间
 * @returns {Object} { startTime: string, endTime: string }
 */
export const getTodayRange = () => {
  const now = new Date()
  const startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0)
  const endOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59)
  
  return {
    startTime: formatDateTime(startOfDay),
    endTime: formatDateTime(endOfDay)
  }
}

/**
 * 获取昨天的开始和结束时间
 * @returns {Object} { startTime: string, endTime: string }
 */
export const getYesterdayRange = () => {
  const now = new Date()
  const yesterday = new Date(now.getTime() - 24 * 60 * 60 * 1000)
  const startOfDay = new Date(yesterday.getFullYear(), yesterday.getMonth(), yesterday.getDate(), 0, 0, 0)
  const endOfDay = new Date(yesterday.getFullYear(), yesterday.getMonth(), yesterday.getDate(), 23, 59, 59)
  
  return {
    startTime: formatDateTime(startOfDay),
    endTime: formatDateTime(endOfDay)
  }
}

/**
 * 获取本周的开始和结束时间（周一到周日）
 * @returns {Object} { startTime: string, endTime: string }
 */
export const getThisWeekRange = () => {
  const now = new Date()
  const dayOfWeek = now.getDay() || 7 // 将周日(0)转换为7
  const startOfWeek = new Date(now.getTime() - (dayOfWeek - 1) * 24 * 60 * 60 * 1000)
  startOfWeek.setHours(0, 0, 0, 0)
  
  const endOfWeek = new Date(startOfWeek.getTime() + 6 * 24 * 60 * 60 * 1000)
  endOfWeek.setHours(23, 59, 59, 999)
  
  return {
    startTime: formatDateTime(startOfWeek),
    endTime: formatDateTime(endOfWeek)
  }
}

/**
 * 判断是否为同一天
 * @param {Date} date1 日期1
 * @param {Date} date2 日期2
 * @returns {boolean} 是否为同一天
 */
export const isSameDay = (date1, date2) => {
  if (!date1 || !date2) return false
  
  return date1.getFullYear() === date2.getFullYear() &&
         date1.getMonth() === date2.getMonth() &&
         date1.getDate() === date2.getDate()
}

/**
 * 计算两个日期之间的天数差
 * @param {Date} startDate 开始日期
 * @param {Date} endDate 结束日期
 * @returns {number} 天数差
 */
export const getDaysDifference = (startDate, endDate) => {
  if (!startDate || !endDate) return 0

  const timeDiff = endDate.getTime() - startDate.getTime()
  return Math.ceil(timeDiff / (1000 * 3600 * 24))
}

/**
 * 根据选择的时间字符串和维度计算时间范围
 * @param {string} selectedTime 选择的时间字符串 (如: '2025-01-15', '2025-01', '2025')
 * @param {string} dimension 时间维度 ('day', 'month', 'year')
 * @returns {Object} { startTime: string, endTime: string }
 */
export const getTimeRangeBySelection = (selectedTime, dimension = 'day') => {
  if (!selectedTime) {
    // 默认返回今天的时间范围
    return getTodayRange()
  }

  try {
    let startDate, endDate

    switch (dimension) {
      case 'day':
        // 按日选择：选中日期的 00:00:00 到 23:59:59
        startDate = new Date(selectedTime + ' 00:00:00')
        endDate = new Date(selectedTime + ' 23:59:59')
        break

      case 'month':
        // 按月选择：选中月份的第一天到最后一天
        const [year, month] = selectedTime.split('-')
        startDate = new Date(parseInt(year), parseInt(month) - 1, 1, 0, 0, 0)
        endDate = new Date(parseInt(year), parseInt(month), 0, 23, 59, 59)
        break

      case 'year':
        // 按年选择：选中年份的1月1日到12月31日
        const yearNum = parseInt(selectedTime)
        startDate = new Date(yearNum, 0, 1, 0, 0, 0)
        endDate = new Date(yearNum, 11, 31, 23, 59, 59)
        break

      default:
        // 默认按日处理
        startDate = new Date(selectedTime + ' 00:00:00')
        endDate = new Date(selectedTime + ' 23:59:59')
    }

    return {
      startTime: formatDateTime(startDate),
      endTime: formatDateTime(endDate)
    }
  } catch (error) {
    console.error('时间范围计算错误:', error)
    // 出错时返回今天的时间范围
    return getTodayRange()
  }
}

/**
 * 解析时间选择字符串，自动判断维度
 * @param {string} selectedTime 选择的时间字符串
 * @returns {Object} { timeRange: {startTime, endTime}, dimension: string }
 */
export const parseTimeSelection = (selectedTime) => {
  if (!selectedTime) {
    return {
      timeRange: getTodayRange(),
      dimension: 'day'
    }
  }

  // 判断时间维度
  let dimension = 'day'
  if (selectedTime.match(/^\d{4}$/)) {
    dimension = 'year'
  } else if (selectedTime.match(/^\d{4}-\d{2}$/)) {
    dimension = 'month'
  } else if (selectedTime.match(/^\d{4}-\d{2}-\d{2}$/)) {
    dimension = 'day'
  }

  const timeRange = getTimeRangeBySelection(selectedTime, dimension)

  return {
    timeRange,
    dimension
  }
}

/**
 * 获取今天的日期字符串
 * @returns {string} 今天的日期 'YYYY-MM-DD'
 */
export const getTodayDateString = () => {
  const today = new Date()
  return formatDateTime(today, 'YYYY-MM-DD')
}
